from volcenginesdkarkruntime import Ark
import os

# 初始化Volcengine Ark客户端
client = Ark(
    api_key="780242c1-b80a-43d1-b5a1-fcc5bea20248",
    # base_url="https://ark.cn-beijing.volces.com/api/v3"
)

def get_user_file_path():
    """获取用户输入的文件路径"""
    while True:
        file_path = input("请输入要转换的Vue文件路径（输入q退出）: ").strip()

        if file_path.lower() == 'q':
            print("已退出程序")
            return None

        if not os.path.exists(file_path):
            print(f"错误：文件 '{file_path}' 不存在，请重新输入")
            continue

        if not file_path.endswith('.vue'):
            print(f"警告：文件 '{file_path}' 不是.vue文件，是否继续？(y/n)")
            confirm = input().strip().lower()
            if confirm != 'y':
                continue

        return file_path

def read_file_content(file_path):
    """读取文件内容"""
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            return file.read()
    except Exception as e:
        print(f"读取文件失败: {e}")
        return None

def generate_vue_component(prompt):
    response = client.chat.completions.create(
        model="deepseek-r1-250120",
        messages=[
            {"role": "system", "content": """你是一个专业的前端架构师，请将AngularJS代码转换为Vue2格式，
            1、其中遇到$http时使用fetch替换
            2、其中遇到baseService时使用request替换,
            这样引入进来：import request from '@/utils/request',
            当baseService的url中,如："${portal}/sys/sysType/v1/getTypesByTypeKeyAndGroupKey?typeKey=engineering_classification&groupKey=RESOURCE_TYPE"
            当遇到${xxx}时转换成${context.xxx}，并且用模板字符串``包起来，转换后是：
            `${context.portal}/sys/sysType/v1/getTypesByTypeKeyAndGroupKey?typeKey=engineering_classification&groupKey=RESOURCE_TYPE`
            
            注意：request.get是get，request.post是post，注意转换
            
            还有，如果是带参数，如：?parentId="+$scope.dataEdit.parentId+"&isRoot="+$scope.dataEdit.isRoot+"&isPriNode="+$scope.dataEdit.isPriNode，
            那么request.post()/request.get()也按照这样带参，不能转换成json形式传参
            
            3、其中遇到$sessionStorage时使用sessionStorage替换
            注意：用户输入的angularjs中的html代码按照我下面的模板代码转换成vue2，并且将代码放到el-dialog中，el-form和el-col不用变
            其中遇到ht-tree使用orgTree替换
            其中遇到input使用ht-input替换
            其中遇到select使用ht-select替换,并且放在ht-form-item中，依此类推
            
            4  这边的代码必须要加el-dialog
            
            5、这边的代码必须要加open方法
            open(data) {
                this.dialogVisible = true;
            }
            
            6、这边的代码必须要加handleClose方法
            handleClose() {
              this.dlg.show = false
            }
            
            7、当遇到<uib-tabset>的时候，使用el-tabs替换
            
            8、当遇到<table>的时候，使用el-tab替换
            
            注意：用户输入的angularjs中的html代码按照我下面的模板代码转换成vue2
            
            <template>
              <el-dialog
                :title="dlg.title"
                :visible.sync="dlg.show"
                :width="width"
                :top="top"
                :close-on-click-modal="false"
                :before-close="handleClose">
                <div>
                  <el-form class="clearfix" :disabled="action === 'view'" v-form data-vv-scope="dlgForm">
                    <template v-if="action === 'edit'">
                      <el-col :span="12" class="com-control-warp">
                        <ht-form-item label="维护人组织">
                          <org-tree
                            v-model="dlgForm.divideId"
                            validate="required"
                            :global="false"
                            @input="handleOrgChange"
                          />
                        </ht-form-item>
                      </el-col>
                      <el-col :span="12" class="com-control-warp">
                        <ht-form-item label="维护人" >
                          <ht-select
                            v-model="dlgForm.followUpId"
                            placeholder="请选择"
                            style="width: 100%"
                            :options="followUpList"
                            :props="{ key: 'key', value: 'name' }"
                            required
                          />
                        </ht-form-item>
                      </el-col>
                    </template>

                    <el-col :span="12" class="com-control-warp">
                      <ht-form-item label="重点客户类型" label-width="130px">
                        <ht-select
                          ref="mainCustomerTypeRef"
                          v-model="dlgForm.mainCustomerType"
                          placeholder="请选择"
                          style="width: 100%"
                          :options="mainCustomerTypeList"
                          :props="{key:'key',value:'name'}"
                          validate='required'
                        />
                      </ht-form-item>
                    </el-col>
                    <el-col :span="12" class="com-control-warp">
                      <ht-form-item label="客户性别" label-width="130px">
                        <ht-select v-model="dlgForm.sex"
                                   placeholder="请选择"
                                   style="width: 100%"
                                   :options="[{key: '0', value: '男'},{key: '1', value: '女'}]"
                                   validate='required'>
                        </ht-select>
                      </ht-form-item>
                    </el-col>

                    <el-col :span="12" class="com-control-warp">
                      <ht-form-item label="客户年龄" label-width="130px">
                        <ht-select v-model="dlgForm.age"
                                   placeholder="请选择"
                                   style="width: 100%"
                                   :options="[{key: '30以内', value: '30以内'},
                                   {key: 1, value: '30-40'},
                                   {key: 1, value: '40-50'},
                                   {key: 1, value: '50以上'}]">
                        </ht-select>
                      </ht-form-item>
                    </el-col>
                    <el-col :span="12" class="com-control-warp">
                      <ht-form-item label="客户名称" label-width="130px">
                        <ht-input
                          v-model="dlgForm.customerName"
                          validate="required"
                          style="width: 100%"
                          :maxlength="30"
                        />
                      </ht-form-item>
                    </el-col>

                    <el-col :span="12" class="com-control-warp">
                      <ht-form-item label="客户电话" label-width="130px">
                        <ht-input
                          v-model="dlgForm.customerMobile"
                          validate="required"
                          style="width: 100%"
                          :maxlength="15"
                        />
                      </ht-form-item>
                    </el-col>
                    <el-col :span="12" class="com-control-warp">
                      <ht-form-item label="客户所属单位" label-width="130px">
                        <ht-input v-model="dlgForm.companyName" style="width: 100%" :maxlength="100" />
                      </ht-form-item>
                    </el-col>

                    <el-col :span="24" class="com-control-warp">
                      <ht-form-item label="单位地址" label-width="130px">
                        <ht-input
                          v-model="dlgForm.companyAddr"
                          type="textarea"
                          style="width: 100%"
                          :maxlength="300"
                        />
                      </ht-form-item>
                    </el-col>

                    <template v-if="action === 'add'">
                      <div class="form-group">
                        <el-col :span="24">
                          <el-button type="success" @click="addCustomerInfo">添加维护人</el-button>
                        </el-col>
                      </div>
                      <div v-for="(item, index) in assistChargePeopleList" :key="index" class="form-group">
                        <el-col :span="12">
                          <ht-form-item :label="`维护人组织${index + 1}`">
                            <ht-input v-model="item.orgName" readonly />
                          </ht-form-item>
                        </el-col>
                        <el-col :span="8">
                          <ht-form-item label="维护人">
                            <ht-input v-model="item.followUpName" readonly />
                          </ht-form-item>
                        </el-col>
                        <el-col :span="4">
                          <el-button type="danger" @click="deleteLeadMan(index)">删除</el-button>
                        </el-col>
                      </div>
                    </template>
                  </el-form>
                </div>

                <span slot="footer" class="dialog-footer">
                  <el-button @click="onCancel">取消</el-button>
                  <ht-submit-button
                    :url="url"
                    :model="saveForm"
                    :request-method="method"
                    scope-name="dlgForm"
                    @after-save-data="afterSaveData"
                    @before-save-data="beforeSaveData">
                    保存
                  </ht-submit-button>
                </span>
              </el-dialog>
            </template>

            <script>
            import OrgTree from '@/components/orgTree/OrgTree'
            import axios from 'axios'

            export default {
              components: {
                OrgTree
              },
              props: {
                width: {
                  type: String,
                  default: '50%'
                },
                top: {
                  type: String,
                  default: '15vh'
                },
                pageParam: {
                  type: Object,
                  default: () => ({})
                }
              },
              data() {
                return {
                  dlg: {
                    show: false,
                    title: '标题'
                  },
                  assistChargePeopleList: [],
                  followUpList: [],
                  mainCustomerTypeList: [],
                  currentUser: JSON.parse(sessionStorage.getItem('currentUser')),
                  method: 'POST',
                  url: '',
                  action: '',
                  saveForm: {},
                  dlgForm: {
                    orgCode: '',
                    followUpId: '',
                    customerName: '',
                    mainCustomerType: '',
                    sex: '',
                    age: '',
                    customerMobile: '',
                    companyName: '',
                    companyAddr: '',
                    orgId: '',
                    divideId: ''
                  },
                  openData: {
                    id: '',
                    title: '',
                    action: '',
                    mainCustomerTypeList: []
                  }
                }
              },
              methods: {
                open(data){
                  this.openData = data
                  this.dlg.show = true
                  this.action = data.action
                  this.dlg.title = data.title
                  this.mainCustomerTypeList = data.mainCustomerTypeList
                  this.$nextTick(() => {
                    if (this.$refs.mainCustomerTypeRef?.changeOptions){
                      this.$refs.mainCustomerTypeRef.changeOptions(data.mainCustomerTypeList)
                    }
                  })

                  // this.url = data.action === 'add'? `${resource}/api/resource/v1/careCustomerInfo/addList`
                  //   : `${resource}/api/resource/v1/careCustomerInfo/update`
                },
                onCancel(){
                  this.dlg.show = false
                  this.$emit('onCancel')
                },
                beforeSaveData(cb){
                  console.log('beforeSaveData=',this.dlgForm)
                  cb(false)
                  return
                },
                afterSaveData () {
                  console.log('---afterSaveData---')
                  this.dlg.show = false
                  this.$emit('onSuccess')
                },
                init() {
                  if (this.pageParam.action === 'add') {
                    this.dlgForm = {
                      orgCode: '',
                      followUpId: '',
                      customerName: '',
                      mainCustomerType: '',
                      sex: '',
                      age: '',
                      customerMobile: '',
                      companyName: '',
                      companyAddr: '',
                      orgId: '',
                      divideId: ''
                    }
                  } else {
                    axios.get(`${resource}/api/resource/v1/careCustomerInfo/get/${this.pageParam.id}`).then(res => {
                      this.dlgForm = res.data
                      this.dlgForm.divideId = res.data.orgId
                    })
                  }
                },
                handleOrgChange(org) {
                  this.dlgForm.divideId = org.id
                  this.dlgForm.orgName = org.name
                },
                async loadFollowUpList(divideId) {
                  const params = {
                    pageBean: { page: 1, pageSize: 99999 },
                    querys: [{ property: 'org.ID_', value: divideId }]
                  }
                  const res = await axios.post(`${uc}/api/org/v1/orgUsers/getOrgUserPage`, params)
                  this.followUpList = res.data.rows.map(item => ({ key: item.userId, name: item.fullName }))
                },
                addCustomerInfo() {
                  this.$emit('add-leadman', {
                    orgName: this.dlgForm.orgName,
                    orgId: this.dlgForm.divideId,
                    followUpId: this.dlgForm.followUpId,
                    followUpName: this.getTypeName(this.dlgForm.followUpId, this.followUpList)
                  })
                },
                deleteLeadMan(index) {
                  this.assistChargePeopleList.splice(index, 1)
                },
                async save() {
                  if (this.action === 'add' && !this.assistChargePeopleList.length) {
                    this.$message.error('请添加维护人!')
                    return
                  }

                  const postData = this.action === 'add'
                    ? this.prepareAddData()
                    : this.prepareUpdateData()

                  try {
                    const res = await this.$submitForm(postData)
                    if (res.code === 0) {
                      this.$emit('on-success')
                      this.dlg.show = false
                    }
                  } catch (error) {
                    this.$message.error(error.message)
                  }
                },
                prepareAddData() {
                  return this.assistChargePeopleList.map(item => ({
                    ...item,
                    mainCustomerTypeName: this.getTypeName(this.dlgForm.mainCustomerType, this.mainCustomerTypeList),
                    ...this.dlgForm
                  }))
                },
                prepareUpdateData() {
                  return {
                    ...this.dlgForm,
                    mainCustomerTypeName: this.getTypeName(this.dlgForm.mainCustomerType, this.mainCustomerTypeList),
                    followUpName: this.getTypeName(this.dlgForm.followUpId, this.followUpList)
                  }
                },
                getTypeName(key, list) {
                  const item = list.find(i => i.key === key)
                  return item ? item.name : ''
                },
                handleClose() {
                  this.dlg.show = false
                  this.$emit('on-cancel')
                }
              }
            }
            </script>

            <style scoped>
            .com-control-warp {
              padding: 8px;
            }
            .form-group {
              margin-bottom: 15px;
            }
            </style>


            只输出转换后完整的代码，不要任何解释"""},
            {"role": "user", "content": prompt}
        ],
        stream=True
    )

    full_content = []
    for chunk in response:
        if chunk.choices:
            content = chunk.choices[0].delta.content
            if content:
                full_content.append(content)

    return "".join(full_content)

def save_converted_code(file_path, vue_code):
    """保存转换后的代码"""
    while True:
        choice = input("请选择保存方式:\n1. 覆盖原文件\n2. 另存为新文件\n3. 不保存\n选择: ").strip()

        if choice == '1':
            # 覆盖原文件
            try:
                with open(file_path, 'w', encoding='utf-8') as file:
                    file.write(vue_code)
                print(f"已成功覆盖原文件: {file_path}")
                return
            except Exception as e:
                print(f"保存文件失败: {e}")
                return

        elif choice == '2':
            # 另存为新文件
            new_path = input("请输入新文件路径: ").strip()
            if not new_path:
                print("无效路径")
                continue

            try:
                # 确保目录存在
                os.makedirs(os.path.dirname(new_path), exist_ok=True)
                with open(new_path, 'w', encoding='utf-8') as file:
                    file.write(vue_code)
                print(f"已成功保存到新文件: {new_path}")
                return
            except Exception as e:
                print(f"保存文件失败: {e}")
                return

        elif choice == '3':
            print("未保存转换结果")
            return

        else:
            print("无效选择，请重新输入")

def main():
    print("Vue文件转换工具")
    print("=" * 30)

    while True:
        # 获取用户输入的文件路径
        file_path = get_user_file_path()
        if not file_path:
            break

        print(f"您选择的文件: {file_path}")

        # 读取文件内容
        angularjs_code = read_file_content(file_path)
        if not angularjs_code:
            continue

        print(f"成功读取文件内容（{len(angularjs_code)} 字符）")

        # 调用转换函数
        vue_code = generate_vue_component(angularjs_code)

        if vue_code:
            print("\n转换后的List Vue代码：\n")
            print(vue_code[:500] + "..." if len(vue_code) > 500 else vue_code)  # 只显示前500字符

            # 询问用户是否保存
            save_choice = input("\n是否保存转换结果？(y/n): ").strip().lower()
            if save_choice == 'y':
                save_converted_code(file_path, vue_code)

        # 询问是否继续转换其他文件
        continue_choice = input("\n是否继续转换其他文件？(y/n): ").strip().lower()
        if continue_choice != 'y':
            print("感谢使用，再见！")
            break

if __name__ == "__main__":
    main()
